import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/networks/course/models/course_response.dart';
import 'package:edu/pages/course/course_detail/course_detail_page_logic.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_tab/video_play/edu_course_video_play_widget_logic.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class EduCoursePageLogic extends ChangeNotifier {
  final int id;

  CourseDetail? courseDetail;
  bool loading = false;
  bool error = false;
  bool get isContentEmpty => courseDetail == null;

  // 课程评价
  int? _lastReviewPage;
  int _reviewPage = 1;
  int _reviewPageSize = 20;
  bool reviewLoading = false;
  bool reviewError = false;
  List<CourseReview>? reviews;

  CancelToken? _reviewCancelToken;

  // 标识是否只获取我的评论
  bool _fetchMyReview = true;
  CourseReview? myReview;

  // 评论是否为空
  bool get isReviewEmpty =>
      (reviews == null || reviews!.isEmpty) && myReview == null;

  // 评论数量
  int get reviewCount => reviews?.length ?? 0;

  // 课程收藏
  bool _favoriteChanging = false;
  bool get isMyFavorite => courseDetail?.isFavorite ?? false;

  // 分页加载课程评价
  bool get canLoadMoreReviews {
    if (_lastReviewPage != null) {
      return _reviewPage <= _lastReviewPage!;
    } else {
      return true;
    }
  }

  // tab,用于显示当前的tab(0: 课程目录, 1: 课程简介, 2: 课程评价)
  int currentTabIndex = 0;

  List<CourseTableContentUnit> categoryUnits = []; // 课程目录分类

  // 视频播放
  late EduCourseVideoPlayWidgetLogic _videoPlayLogic;
  EduCourseVideoPlayWidgetLogic get videoPlayLogic => _videoPlayLogic;
  int get currentVideoId => _videoPlayLogic.videoIdNotifier.value;

  // 同步视屏播放进度相关
  int get currentVideoPercent => _videoPlayLogic.progressNotifier.value.round();

  EduCoursePageLogic({required this.id});

  void init() {
    _videoPlayLogic = EduCourseVideoPlayWidgetLogic(id);
    _videoPlayLogic.videoIdNotifier.addListener(() {
      notifyListeners();
    });
    _videoPlayLogic.progressNotifier.addListener(() {
      notifyListeners();
    });

    Future.delayed(Duration.zero, () {
      loadCourseDetail();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _reviewCancelToken?.cancel();
  }

  void changeTabIndex(int index) {
    currentTabIndex = index;
    if (index == 2 && reviews == null) {
      // 获取课程评价
      loadReviews();
    }
    notifyListeners();
  }

  // 赋值我的评价
  void assignMyReview(CourseReview review) {
    myReview = review;
    notifyListeners();
  }

  // 播放视频
  void playVideo(int videoId) async {
    if (videoId == currentVideoId) {
      return;
    }
    _videoPlayLogic.loadVideo(videoId);
  }

  // 加载课程评价
  void loadReviews() async {
    try {
      if (reviewLoading) {
        return;
      }
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      reviewLoading = true;
      reviewError = false;
      notifyListeners();

      final response = await DataFetcher.shared.businessApi.getCourseReviews(
        courseId: id,
        fetchMyReview: _fetchMyReview,
        page: _reviewPage,
        pageSize: _reviewPageSize,
        cancelToken: _reviewCancelToken,
      );
      _fetchMyReview = false;
      reviewLoading = false;
      EasyLoading.dismiss();

      if (response.code == 0) {
        final newRecords = response.reviews ?? [];
        final accountId = AccountInfo.shared.accountId ?? 0;
        newRecords.removeWhere((element) => element.userId == accountId);

        if (reviews == null) {
          reviews = newRecords;
        } else {
          reviews!.addAll(newRecords);
        }
        _lastReviewPage = response.pageMeta?.lastPage;
        _reviewPage = (response.pageMeta?.currentPage ?? _reviewPage) + 1;
        _reviewPageSize = response.pageMeta?.pageSize ?? 20;

        if (response.myReview != null) {
          myReview = response.myReview;
        }
      } else {
        reviewError = true;
        EasyLoading.showError(response.message ?? AppStrings.reviewError);
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      if (e.type == DioExceptionType.cancel) {
        return;
      }
      reviewLoading = false;
      reviewError = true;
      notifyListeners();
      EasyLoading.showError(e.toString());
      log('Error: $e');
    } catch (e) {
      EasyLoading.dismiss();
      reviewLoading = false;
      reviewError = true;
      notifyListeners();
      log('Error: $e');
    }
  }

  // 加载课程详情
  void loadCourseDetail() async {
    try {
      if (loading) return;

      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      loading = true;
      error = false;
      notifyListeners();

      final response = await DataFetcher.shared.courseApi.getCourseDetail(id);
      EasyLoading.dismiss();
      loading = false;

      if (response.code == 0) {
        courseDetail = response.course;
        error = false;
        await _makeCategoryUnits();
      } else {
        error = true;
        EasyLoading.showError(response.message ?? AppStrings.courseDetailError);
      }
      notifyListeners();
    } catch (e) {
      loading = false;
      error = true;
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      notifyListeners();
    }
  }

  // 构建目录分类
  Future<void> _makeCategoryUnits() async {
    final chapters = courseDetail?.chapters;
    if (chapters == null) {
      return;
    }
    categoryUnits.clear(); // 清空

    var firstVideoId = 0;
    for (final chapter in chapters) {
      // 章节---第几章 xxxx
      final chapterTitle =
          '${AppStrings.chapterIndex(chapter.index)} ${chapter.title}';

      categoryUnits.add(
        CourseTableContentUnit(
          id: chapter.id,
          title: chapterTitle,
          isChapter: true,
          isFree: false,
        ),
      );

      // 视频-- xxxxx(00:00)
      for (final item in chapter.videos ?? []) {
        final cIndex = chapter.index; // 章节索引
        final vIndex = item.index; // 视频索引
        final vTitle = item.title; // 视频标题
        final vMinutes = item.duration ~/ 60; // 分钟
        final vSeconds = (item.duration % 60).toString().padLeft(2, '0'); // 秒
        final videoTitle = '$cIndex-$vIndex $vTitle';
        final timeString = '($vMinutes:$vSeconds)';

        categoryUnits.add(
          CourseTableContentUnit(
            id: item.id,
            title: videoTitle,
            timeString: timeString,
            isChapter: false,
            isFree: true,
          ),
        );
        if (firstVideoId == 0) {
          firstVideoId = item.id;
        }
      }
    }

    // 构建第一个视频的媒体信息
    await _videoPlayLogic.makeFirstVideoMedia(firstVideoId);
  }

  // 课程收藏
  void toggleFavorite() async {
    if (_favoriteChanging) {
      return;
    }
    _favoriteChanging = true;

    try {
      if (isMyFavorite) {
        final response = await DataFetcher.shared.businessApi
            .removeFavoriteCourse(id);
        if (response.code == 0) {
          courseDetail?.isFavorite = false;
          EasyLoading.showSuccess(AppStrings.ddFavoriteCancelSuccess);
          notifyListeners();
        } else {
          log(response.message ?? AppStrings.unknownError);
        }
      } else {
        final response = await DataFetcher.shared.businessApi.addFavoriteCourse(
          id,
        );
        if (response.code == 0) {
          courseDetail?.isFavorite = true;
          EasyLoading.showSuccess(AppStrings.ddFavoriteSuccess);
          notifyListeners();
        } else {
          log(response.message ?? AppStrings.unknownError);
        }
      }
    } catch (e) {
      log('toggleFavorite error: $e');
    } finally {
      _favoriteChanging = false;
    }
  }
}
